//
//  CYTextField.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/1.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYTextField.h"

@interface CYTextField()<UITextFieldDelegate>
@property (nonatomic, strong) CYLabel *detailPlaceholderLBL;
@property (nonatomic, assign) CGFloat offset_width;
@property (nonatomic, assign) CGFloat offset_height;
@end
@implementation CYTextField
- (instancetype)initWithPlaceholder:(NSString *)placeholder{
    self = [super init];
    if (self) {
        self.delegate = self;
        self.placeholder = placeholder;
        self.borderStyle = UITextBorderStyleNone;
        self.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.font = [UIFont systemFontOfSize:AL(PT(28))];
        self.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
        self.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
        self.line.hidden  = NO;
        
    }
    
    return self;
}
- (instancetype)initWithLeftImage:(NSString *)image Placeholder:(NSString *)placeholder{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.delegate = self;
        self.placeholder = placeholder;
        self.borderStyle = UITextBorderStyleNone;
        self.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.font = [UIFont systemFontOfSize:AL(PT(28))];
        self.contentVerticalAlignment = UIControlContentVerticalAlignmentBottom;
        self.line.hidden  = NO;
        self.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
        [self setupLeftImage:image];
    }
    return self;
}
/*银行转账，填写资料的textfield*/
- (instancetype)initWithPlaceholder:(NSString *)placeholder color:(UIColor *)color size:(CGFloat)size{
    self = [super init];
    if (self) {
        self.delegate = self;
        self.placeholder = placeholder;
        self.borderStyle = UITextBorderStyleNone;
        self.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.font = [UIFont systemFontOfSize:size];
        [self setValue:color forKeyPath:@"_placeholderLabel.textColor"];
        [self setValue:[UIFont systemFontOfSize:size] forKeyPath:@"_placeholderLabel.font"];
        self.autocapitalizationType = UITextAutocapitalizationTypeNone;//字母不自动大写
    }
    return self;
    
}

- (CYView *)line{
    if (!_line) {
        _line = [[CYView alloc]initWithColor:[UIColor lightGrayColor]];
        [self addSubview:_line];
        
        [_line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).with.offset(0);
            make.bottom.equalTo(self.mas_bottom).with.offset(0);
            make.right.equalTo(self.mas_right).with.offset(0);
            make.height.mas_equalTo(0.5);
        }];
    }
    return _line;
}

- (CYLabel *)detailPlaceholderLBL{
    if (!_detailPlaceholderLBL) {
        CGFloat width = [self.placeholder sizeWithAttributes:@{NSFontAttributeName:self.font}].width;
        _detailPlaceholderLBL  = [[CYLabel alloc]initWithText:_detail_placeholder size:_detail_placeholder_size weight:UIFontWeightUltraLight];
        _detailPlaceholderLBL.textColor = _detail_placeholder_color;
        [self addSubview:_detailPlaceholderLBL];
        
        [_detailPlaceholderLBL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).with.offset(AL(width + _offset_width));
            make.bottom.equalTo(self.mas_bottom).with.offset(- AL(_offset_height));
            make.size.mas_equalTo(_detailPlaceholderLBL.bounds.size);
        }];
    }
    
    return _detailPlaceholderLBL;
}

- (void)setOffset_height:(CGFloat)offset_height{
    if (_offset_height != offset_height) {
        _offset_height = offset_height;
        if (_offset_height !=0 && _offset_width != 0) {
            self.detailPlaceholderLBL.hidden = NO;
        }
    }
    
}
- (void)setupLeftImage:(NSString *)image{
    self.leftView= [[CYImageView alloc]initWithImage:[UIImage imageNamed:image]];
    self.leftViewMode = UITextFieldViewModeAlways;//用来设置leftview的显示时机
    
}
- (void)setupRightview:(NSString *)imageName{
    self.rightView = [[CYImageView alloc]initWithImage:[UIImage imageNamed:imageName]];
    self.rightViewMode = UITextFieldViewModeAlways;
    
}

- (void)hiddenDetailPlaceholderLBL:(BOOL)ishidden{
    _detailPlaceholderLBL.hidden = ishidden;
}
//设置left的位置
- (CGRect)leftViewRectForBounds:(CGRect)bounds{
    
    CGRect iconRect = [super leftViewRectForBounds:bounds];
    iconRect.origin.x += 5;
    iconRect.origin.y = self.bounds.size.height - self.leftView.bounds.size.height - AL(12) ;
    return iconRect;
}

//设置right的位置
- (CGRect)rightViewRectForBounds:(CGRect)bounds{
    CGRect iconRect = [super rightViewRectForBounds:bounds];
    
    if (self.contentVerticalAlignment == UIControlContentVerticalAlignmentBottom) {
        iconRect.origin.x -= 5;
        iconRect.origin.y = self.bounds.size.height - self.rightView.bounds.size.height - AL(12) ;
        return iconRect;
    }
    else
        return iconRect;
}

//阴影文字与输入框的距离
- (CGRect)textRectForBounds:(CGRect)bounds{
    
    if (self.textAlignment == NSTextAlignmentRight) {
        return CGRectInset(bounds, AL(PT(20)), 0);
    }
    _offset_width = (self.leftView)?self.leftView.bounds.size.width + 10:0.0;
    self.offset_height = (self.leftView)?10:0;
    return CGRectInset(bounds, AL(_offset_width), AL(_offset_height)); //文字左边与leftview右边距离10
    
}

//编辑时候，阴影文本的位置
- (CGRect)editingRectForBounds:(CGRect)bounds{
    
    if (self.textAlignment == NSTextAlignmentRight) {
        return CGRectInset(bounds, AL(PT(20)), 0);
    }
    return CGRectInset(bounds, AL(_offset_width), AL(_offset_height)); //文字左边与leftview右边距离10
}

// 添加通知监听见键盘弹出/退出
- (void)registerNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

- (void)releaseNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

//弹出键盘时候，判断是否遮挡输入框，
- (void)keyboardWillShow:(NSNotification *)notification{
    if (!self.editing)
        return;
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyboardHeight = [aValue CGRectValue].size.height;//键盘的高度
    //获取键盘动画时间
    float time = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //输入框在当前屏幕的坐标y
    CGFloat originMaxY = CGRectGetMaxY([self convertRect:self.bounds toView:[[[UIApplication sharedApplication] delegate] window]]);
    //判断是非遮挡当前输入框，大于0遮挡，小于0没有
    CGFloat map = originMaxY + keyboardHeight - SCREEN_HEIGHT;
    
    if (_cydelegate && [_cydelegate respondsToSelector:@selector(heightWhenKeyboardChange:animationInterval:)])
        [_cydelegate heightWhenKeyboardChange:map animationInterval:time];
}


- (void)setupLineWhenBeginEditing{
    if (_line) {
        _line.backgroundColor = THEME_COLOR;//开始编辑，下划线变主题颜色
        [_line mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(1);//开始编辑,下划线变粗
        }];
    }
}

- (void)setupLineWhenEndEditing{
    if (_line) {
        _line.backgroundColor = [UIColor lightGrayColor];//结束编辑,下划线恢复灰色
        [_line mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0.5);//结束编辑,下划线变细
        }];
    }
}
#pragma - mark - CYTextFieldDelegate - method
//- (void)heightWhenKeyboardChange:(CGFloat)height{
//
//}

#pragma mark UITextFieldDelegate 事件
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [self registerNotification];//注册通知
    [self setupLineWhenBeginEditing];//设置下划线颜色
    if (_cydelegate && [_cydelegate respondsToSelector:@selector(textFieldShouldBeginEditing:)])
        return [_cydelegate textFieldShouldBeginEditing:textField];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];//取消第一响应者
    [self releaseNotification];//释放通知
    if (_cydelegate && [_cydelegate respondsToSelector:@selector(textFieldShouldReturn:)])
        return [_cydelegate textFieldShouldReturn:textField];
    
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (_cydelegate && [_cydelegate respondsToSelector:@selector(textField: shouldChangeCharactersInRange: replacementString:)])
        return [_cydelegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
    return YES;
}   // return NO to not change text

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [self setupLineWhenEndEditing];
    if (_cydelegate && [_cydelegate respondsToSelector:@selector(textFieldDidEndEditing:)])
        [_cydelegate textFieldDidEndEditing:textField];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
